#!/usr/bin/python

import os, sys, time
from SOAPpy import SOAPProxy

def usage():
    print "ivic-vprocess [view|run <software> <user> <display>]"

class VProcessServerProxy(object):
    
    def __init__(self,server = None):
        if server == None: self.server = "127.0.0.1:8080"
        self.proxy = SOAPProxy('http://%s/vprocess' %self.server)
        
    def create(self,user, software, display):
        try:
            op = getattr(self.proxy, 'createVProcess')
            #args = {'user':user, 'software':software, 'display':display}
            retval = op(user, software, display)
            print repr(retval)
        except Exception, e:
            print e
            
    def clean(self):
        try:
            op = getattr(self.proxy, 'cleanVProcess')
            retval = op()
        except Exception,e:
            print e
        
    def kill(self,pid):
        try:
            op = getattr(self.proxy, 'killVProcess')
            retval = op(pid)
        except Exception,e:
            print e
            
    def query(self,user, software):
        op = getattr(self.proxy, 'queryVProcess')
        retval = op(user, software)
        for each in retval: print each
        
    def queryAll(self):
        op = getattr(self.proxy, 'queryAllVProcess')
        retval = op()
        for each in retval: print each
    
def proxymain(argv):
    try:
        proxy = VProcessServerProxy()
    except:
        print "server not started"
        return
    
    if len(argv) <= 1: 
        usage()
        return
    else:
        argv = argv[1:]
        
    if argv[0] == 'run':
        try:
            softname = argv[1]
            user = argv[2]
            vspace = argv[3]
        except:
            print "argument error"
            return
        
        try:
            proxy.create(user,softname,vspace)
        except Exception,e:
            print e
            
    elif argv[0] == 'view':
        try:
            proxy.queryAll()
        except:
            pass
    elif argv[0] == 'kill':
        try:
            proxy.kill(argv[1])
        except Exception,e:
            print e
            
    elif argv[0] == 'clean':
        try:
            proxy.clean()
        except Exception,e:
            print e
            
    else:
        #to be done with other options
        pass